/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tradeplus.security;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.apache.commons.lang.StringUtils;

/**
 *
 * @author ronnie
 */
public class BTPAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    
    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "j_username";
    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "j_password";
    public static final String SPRING_SECURITY_FORM_SITE_KEY = "j_site";
    public static final String SPRING_SECURITY_FORM_DOMAIN_KEY = "j_domain";
    public static final String SPRING_SECURITY_LAST_USERNAME_KEY = "SPRING_SECURITY_LAST_USERNAME";
    
    private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
    private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;
    
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String username = obtainUsername(request);
        String password = obtainPassword(request);
        String site = request.getParameter(SPRING_SECURITY_FORM_SITE_KEY);
        String domain = request.getParameter(SPRING_SECURITY_FORM_DOMAIN_KEY);
        
        if (username == null) username = "";
        if (password == null) password = "";
        
        username = username.trim();
        
        BTPAuthenticationToken btpAuthToken = new BTPAuthenticationToken(username, password, site, domain);
        
        HttpSession session = request.getSession(false);
        
        if (session != null || getAllowSessionCreation()) {
            request.getSession().setAttribute(SPRING_SECURITY_LAST_USERNAME_KEY, StringUtils.escape(username));
        }
        
        setDetails(request, btpAuthToken);
        
        return this.getAuthenticationManager().authenticate(btpAuthToken);
    }
    
    protected void setDetails(HttpServletRequest request, BTPAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }
}
